import React from 'react'
import { UdPageHeader, UdFilter, UdDatePicker, http, validators, UdTable } from '@/lib'
import { Button, Table, Select, Spin, Statistic, message, Alert } from 'antd'
import apis from '@/apis/FundsManage'
import comApis from '@/apis'
import './index.scss'
import { downBlobFile } from '@/utils/methods'
import qs from 'qs'
import UdSelect from '@/components/UdFormControls/UdSelect'
import { WrappedFormUtils } from 'antd/lib/form/Form'
import { getBrandSelectList, getDealerListByBrand } from '@/common/Request'
import moment from 'moment'

const fieldMap = {
  //开始时间
  startTime: "startDate",
  //结束时间
  endTime: "endDate",

  //记账日期
  bookkeepingDate: "recordDate",
  //凭证编号
  documentNo: "id",
  //借方
  debit: "lendMoney",
  //贷方
  lender: "loanMoney",
  //余额
  balance: "balance",
  //备注
  remark: "description",
}

const style = { borderBottom: "2px solid #00c1de", color: "#00c1de" }

//资金汇总字段
const fundsMsg = [
  {
    label: "订单总金额",
    key: "ddze"
  },
  {
    label: "订单开票金额",
    key: "ddkpe"
  },
  {
    label: "订单占用未开票金额",
    key: "ddwkp"
  },
  {
    label: "汇票成本",
    key: "hpcb"
  },
  {
    label: "已收取",
    key: "ysqje"
  },
  {
    label: "汇票利息占用",
    key: "hplx"
  },
  {
    label: "未到期票据",
    key: "wdqpj"
  },
  {
    label: "可退款金额",
    key: "ktkje"
  },
  {
    label: "特批额度",
    key: "tped"
  },
  {
    label: "股本担保赊销",
    key: "gqje"
  }
]

export default class List extends React.Component {

  private filterForm: WrappedFormUtils

  private initSummaryData = {
    bukrs: 0,//      公司代码   　
    kunnr: 0,//   客户编号
    ksyye: 0,//    客户可用余额 2位小数
    kjzmye: 0,//   当前财务余额 2位小数
    sjye: 0,//     客户实际余额 2位小数
    ddze: 0,//     订单总金额  2位小数
    ddkpe: 0,//    订单开票金+++++++++++++++++++++++++ 额    2位小数
    ddwkp: 0,//    订单占用未开票金额  2位小数
    sxed: 0,//     赊销额度   2位小数
    tped: 0,//     特批额度   2位小数
    hpcb: 0,//     汇票成本   2位小数
    ysqje: 0,//    已收取    2位小数
    hplx: 0,//     汇票利息占用 2位小数
    wdqpj: 0,//    未到期票据  2位小数
    gqje: 0,//     股本担保赊销 2位小数
    ktkje: 0//    可退款金额  2位小数
  }

  state = {
    searchValues1: {
      brandCodes: undefined,
      dealerCode: undefined,
      endDate: moment().format("YYYYMMDD") // 汇总截止日期格式yymmdd
    },
    searchValues: {
      brandCodes: undefined,
      dealerCode: undefined,
      startDate: `${moment().format("YYYY")}-01-01 00:00:00`,
      endDate: moment().format("YYYY-MM-DD 23:59:59")
    },
    tableData: [],
    page: 1,
    size: 10,
    total: 0,
    type: "汇总",
    summaryData: { ...this.initSummaryData },
    loading: false,
    dealerCodeOptions: [],
    brandOptions: [],
    contactsCount: { // 往来账明细合计数据
      lendMoney: 0, // 借方
      loanMoney: 0, // 贷方
      balance: 0, // 余额
    },
  }

  /* componentWillMount() {
    if (this.state.type === "汇总") {

      this.getDetailsData()

    }
  } */

  componentDidMount() {
    this.getBrandList()
  }

  private getBrandList = () => {
    getBrandSelectList().then(result => {
      this.setState({
        brandOptions: result,
      })
    })
  }

  private getDealerListByBrand = (code) => {
    // 组织切换，重置经销商条件
    this.filterForm.setFieldsValue({ dealerCode: undefined })
    getDealerListByBrand(code).then(result => {
      this.setState({
        dealerCodeOptions: result,
      })
    })
  }

  //更新汇总数据
  private getDetailsData = () => {
    if (!this.state.brandOptions || this.state.brandOptions.length == 0) {
      // 账户下一个组织的资金权限都没有则不获取数据（该模块获取数据必须默认有一个组织）
      return
    }
    this.setState({
      loading: true
    })
    // 资金汇总截止时间格式为yyMMdd
    let brandCodes = this.state.searchValues1?.brandCodes ? [this.state.searchValues1.brandCodes] : undefined
    let endDate = this.state.searchValues1?.endDate && moment(this.state.searchValues1.endDate).format('YYYYMMDD')

    http.post(apis.summary, {
      ...this.state.searchValues1,
      brandCodes, endDate
    },
      {
        paramsSerializer: function (params) {
          return qs.stringify(params, { arrayFormat: 'repeat' })
        }
      }).then(res => {
        this.setState({ summaryData: res.data })
      }).finally(() => this.setState({ loading: false }))
  }

  //更新列表数据
  private getList = async () => {
    if (!this.state.brandOptions || this.state.brandOptions.length == 0) {
      // 账户下一个组织的资金权限都没有则不获取数据（该模块获取数据必须默认有一个组织）
      return
    }

    this.setState({
      loading: true
    })

    let brandCodes = this.state.searchValues?.brandCodes ? [this.state.searchValues.brandCodes] : undefined
    let startDate = this.state.searchValues?.startDate && moment(this.state.searchValues?.startDate).format("YYYY-MM-DD 00:00:00")
    let endDate = this.state.searchValues?.endDate && moment(this.state.searchValues?.endDate).format("YYYY-MM-DD 23:59:59")
    try {
      let list: any = await http.post(apis.getFundsList, {
        page: this.state.page, size: this.state.size, ...this.state.searchValues, startDate, brandCodes, endDate
      },
        {
          paramsSerializer: function (params) {
            return qs.stringify(params, { arrayFormat: 'repeat' })
          }
        })

      let listAll: any = await http.post(apis.detailTotal, {
        page: this.state.page, size: this.state.size, ...this.state.searchValues, startDate, brandCodes, endDate
      },
        {
          paramsSerializer: function (params) {
            return qs.stringify(params, { arrayFormat: 'repeat' })
          }
        })

      listAll = listAll?.data
      /* const tableData = list.data?.content && list.data.content.length ? [{
        credentialCode: "合计",
        lendMoney: listAll?.lendMoney,
        loanMoney: listAll?.loanMoney,
        balance: listAll?.balance,
        description: listAll?.description
      }, ...list.data.content] : [] */
      const tableData = list.data?.content

      this.setState({
        tableData,
        page: list.data.number,
        size: list.data.size,
        total: list.data.totalElements,
        loading: false,
        contactsCount: {
          lendMoney: listAll?.lendMoney || 0,
          loanMoney: listAll?.loanMoney || 0,
          balance: listAll?.balance || 0,
        },
      })
    } catch (error) {
      this.setState({
        loading: false
      })
    }
  }

  //分页,修改每页显示条数
  private handleChangePage = (pagination) => {
    const { current: page, pageSize: size } = pagination
    this.setState({ page, size }, () => {
      // this.getList()
    })
  }

  //搜索
  private handleSearch = (values, type) => {
    /* values = Object.keys(values).reduce((pre, cur) => {
      if (cur !== "brandCodes") {
        return {
          ...pre,
          [cur]: moment(values[cur]).format("YYYY-MM-DD HH:mm:ss")
        }
      }
      return { ...pre, [cur]: values[cur] }
    }, {}) */
    if (type === 1) {

      if (values?.endDate1) {
        values.endDate = values.endDate1
        delete values.endDate1
      }

      this.setState({ searchValues1: { ...values }, page: 1 }, () => {
        if (this.state.type === "汇总") {
          this.getDetailsData()
        } else {
          this.getList()
        }
      })
    } else {
      this.setState({ searchValues: { ...values }, page: 1 }, () => {
        if (this.state.type === "汇总") {
          this.getDetailsData()
        } else {
          this.getList()
        }
      })
    }


  }

  //导出
  private exportSummaryData = () => {
    if (this.state.type === "汇总") {
      const { brandCodes: brandCode, dealerCode } = this.state.searchValues1
      if (!brandCode || !dealerCode) {
        message.error('请选择销售组织和经销商查询后操作')
        return
      }
      let brandCodes = this.state.searchValues1?.brandCodes ? [this.state.searchValues1.brandCodes] : undefined
      let endDate = this.state.searchValues1?.endDate && moment(this.state.searchValues1.endDate).format('YYYYMMDD')

      http.post(apis.summaryExport, {
        ...this.state.searchValues1, brandCodes, endDate
      },
        {
          responseType: "arraybuffer",
          paramsSerializer: function (params) {
            return qs.stringify(params, { arrayFormat: 'repeat' })
          }
        }).then(res => {
          if (!res.data.code) {
            downBlobFile(res.data, "资金汇总单")
          }
        })
    } else {
      const { brandCodes: brandCode, dealerCode } = this.state.searchValues
      if (!brandCode || !dealerCode) {
        message.error('请选择销售组织和经销商查询后操作')
        return
      }
      let brandCodes = this.state.searchValues?.brandCodes ? [this.state.searchValues.brandCodes] : undefined
      let startDate = this.state.searchValues?.startDate && moment(this.state.searchValues?.startDate).format('YYYY-MM-DD 00:00:00')
      let endDate = this.state.searchValues?.endDate && moment(this.state.searchValues?.endDate).format('YYYY-MM-DD 23:59:59')

      http.post(apis.detailDownload, {
        page: this.state.page, size: this.state.size, ...this.state.searchValues, brandCodes, startDate, endDate
      },
        {
          paramsSerializer: function (params) {
            return qs.stringify(params, { arrayFormat: 'repeat' })
          },
          responseType: "arraybuffer",
        },
      ).then(res => {
        if (!res.data.code) {
          downBlobFile(res.data, "资金明细单")
        }
      })
    }

  }

  private resetFilterHandle = () => {
    this.setState({
      tableData: [],
      summaryData: { ...this.initSummaryData },
      contactsCount: {
        lendMoney: 0,
        loanMoney: 0,
        balance: 0,
      },
      page: 1,
      total: 0,
    })
  }

  private switchTypeHandle = (e: any) => {
    this.filterForm.resetFields()
    this.setState({
      type: e.target.dataset.id
    })
    this.resetFilterHandle()
  }

  render() {
    return <div className="funds-list-box">
      <UdPageHeader title="我的资金" subTitle="数据仅供参考，最终以财务提供为准" subTitleColor={'red'} />
      <div className="table-front-btns-box">
        <div className="type-change-box" onClick={this.switchTypeHandle}>
          <span data-id="汇总" style={this.state.type === "汇总" ? style : {}}>资金汇总</span>
          <span data-id="明细" style={this.state.type === "汇总" ? {} : style}>往来账明细</span>
        </div>
      </div>
      {
        this.state.type === "汇总" ?
          <>
            <UdFilter
              items={[
                {
                  id: 'brandCodes',
                  label: "销售组织",
                  rules: [validators.required],
                  render: <UdSelect onChange={this.getDealerListByBrand} options={this.state.brandOptions} allowClear={false} />
                },
                {
                  id: "dealerCode",
                  label: "经销商",
                  rules: [validators.required],
                  render: <UdSelect allowClear={false} showSearch={true} options={this.state.dealerCodeOptions} />
                },
                {
                  id: 'endDate',
                  label: "截止时间",
                  initialValue: moment(moment().format('YYYYMMDD')),
                  decoratorOptions: { getValueFromEvent: (date) => date && moment(date).format('YYYYMMDD') },
                  render: <UdDatePicker />
                }
              ]}
              onSearch={(values) => { this.handleSearch(values, 1) }}
              resetAfter={this.resetFilterHandle}
              loading={this.state.loading}
              getForm={(form) => this.filterForm = form}
            />
            <div className="export-btn"><Button onClick={() => { this.exportSummaryData() }} type="primary">导出</Button></div>
            <Spin spinning={this.state.loading}>
              <ul className="funds-show-box">
                <li><span>当前财务余额</span><span>{(this.state.summaryData.kjzmye || this.state.summaryData.kjzmye == 0) && <Statistic value={this.state.summaryData.kjzmye} precision={2} />}</span></li>
                <li><span>客户实际余额</span><span>{(this.state.summaryData.sjye || this.state.summaryData.sjye == 0) && <Statistic value={this.state.summaryData.sjye} precision={2} />}</span></li>
                <li><span>客户可用余额</span><span>{(this.state.summaryData.ksyye || this.state.summaryData.ksyye == 0) && <Statistic value={this.state.summaryData.ksyye} precision={2} />}</span></li>
              </ul>
              <div className="table-area">
                <UdTable
                  rowKey={(record, index) => index + ""}
                  dataSource={[this.state.summaryData]}
                  columns={[
                    {
                      dataIndex: "kjzmye",
                      title: "当前财务余额"
                    },
                    {
                      dataIndex: "ddze",
                      title: "订单总金额",
                    },
                    {
                      dataIndex: "ddkpe",
                      title: "订单开票金额"
                    },
                    {
                      dataIndex: "ddwkp",
                      title: "订单占用未开票金额",
                    },
                    {
                      dataIndex: "hpcb",
                      title: "汇票成本",
                    },
                    {
                      dataIndex: "ysqje",
                      title: "已收取",
                    },
                    {
                      dataIndex: "hplx",
                      title: "汇票利息占用"
                    },
                    {
                      dataIndex: "sjye",
                      title: "客户实际余额"
                    },
                    {
                      dataIndex: "wdqpj",
                      title: "未到期票据"
                    },
                    {
                      dataIndex: "ktkje",
                      title: "可退款金额"
                    },
                    {
                      dataIndex: "tped",
                      title: "特批额度"
                    },
                    {
                      dataIndex: "gqje",
                      title: "股本担保赊销"
                    },
                  ]}
                  pagination={false}
                  scroll={{ x: true }}
                />
              </div>
              <div className="descript-text">
                <p className="title">主要字段说明：</p>
                <p>1、订单占用未开票金额=订单总金额-订单开票金额</p>
                <p>2、汇票利息占用：应收还未收的汇票利息金额，汇票利息占用=汇票成本-已收款</p>
                <p>3、客户实际余额=当前财务余额-订单占用未开票金额-汇票利息占用</p>
                <p>4、可退款金额：办理现金退款的金额，可退款金额=客户实际余额-未到期票据</p>
                <p>5、客户可使用额度：可以下单订货的额度，客户可使用额度=客户实际余额+特批额度+股本担保赊销</p>
              </div>
              {/* <div className="msg-box">
                {
                  fundsMsg.map((item, index) => <div key={index}>
                    <span>{item.label}：</span>
                    <span>{(this.state.summaryData[item.key] || this.state.summaryData[item.key] == 0) && <Statistic value={this.state.summaryData[item.key]} precision={2} />}</span>
                  </div>)
                }
              </div> */}
            </Spin>
          </> :
          <>
            <UdFilter
              items={[
                {
                  id: 'brandCodes',
                  label: "销售组织",
                  rules: [validators.required],
                  render: <UdSelect onChange={this.getDealerListByBrand} allowClear={false} options={this.state.brandOptions} />
                },
                {
                  id: "dealerCode",
                  label: "经销商",
                  rules: [validators.required],
                  render: <UdSelect allowClear={false} showSearch={true} options={this.state.dealerCodeOptions} />
                },
                {
                  id: fieldMap.startTime,
                  label: "开始时间",
                  initialValue: moment(`${moment().format("YYYY")}-01-01 00:00:00`),
                  render: <UdDatePicker />
                },
                {
                  id: fieldMap.endTime,
                  label: "结束时间",
                  initialValue: moment(moment().format('YYYY-MM-DD 23:59:59')),
                  render: <UdDatePicker />
                }
              ]}
              onSearch={(values) => {
                this.handleSearch(values, 2)
              }}
              resetAfter={this.resetFilterHandle}
              loading={this.state.loading}
              getForm={(form) => this.filterForm = form}
            />
            <div className="export-btn"><Button type="primary" onClick={() => { this.exportSummaryData() }}>导出</Button></div>
            <Alert
              className="moneycount-extra-tips"
              message={<div>合计：借方 <span className="num">{this.state.contactsCount.lendMoney}</span>，贷方 <span className="num">{this.state.contactsCount.loanMoney}</span>，余额 <span className="num">{this.state.contactsCount.balance}</span></div>}
            />
            <Table
              className="has-sum-table"
              rowKey={(record, index) => index + ""}
              dataSource={this.state.tableData}
              loading={this.state.loading}
              columns={[
                {
                  dataIndex: "brandName",
                  title: "销售组织"
                },
                {
                  dataIndex: "recordDate",
                  title: "记账日期",
                },
                {
                  dataIndex: "credentialCode",
                  title: "参照凭证"
                },
                {
                  dataIndex: 'lendMoney',
                  title: "借方",
                  align: 'right',
                },
                {
                  dataIndex: 'loanMoney',
                  title: "贷方",
                  align: 'right',
                },
                {
                  dataIndex: 'balance',
                  title: "余额",
                  align: 'right',
                },
                {
                  dataIndex: 'description',
                  title: "备注"
                }
              ]}
              onChange={this.handleChangePage}
              pagination={{
                current: this.state.page,
                pageSize: this.state.size,
                total: this.state.total,
                showQuickJumper: true,
                showSizeChanger: true,
                pageSizeOptions: ['10', '20', '30', '40'],
                showTotal: (total, range) => `共${total}项，当前${range[0]}-${range[1]}项`,
              }}
            />
          </>
      }
    </div>
  }
}